package de.lulusoft.anothertorrent.gui.wizards;

import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;

import de.lulusoft.anothertorrent.core.AnotherTorrentCore;
import de.lulusoft.anothertorrent.core.servers.Server;
import de.lulusoft.anothertorrent.core.servers.ServerManager;
import de.lulusoft.anothertorrent.gui.views.ServerView;

public class NewServerWizard extends Wizard{
	
	public static final String ID = "de.lulusoft.anothertorrent.gui.wizards.NewServerWizard";
	
	protected NewXmlRcpServerWizardPage newXmlRcpServerWizardPage = null;
	protected NewSocketServerWizardPage newSocketServerWizardPage = null;
	protected SelectServerTypeWizardPage selectServerTypeWizardPage = null;
	protected WizardPage usedServerPage = null;
	
	protected boolean edit = false;
	protected Server server = null;
	

	public NewServerWizard() {
		super();
		setWindowTitle(Messages.NewServerWizard_1);
	}

	@Override
	public boolean canFinish() {
		boolean finish = false;
		if (selectServerTypeWizardPage.isPageComplete())
		{
			if (usedServerPage instanceof NewXmlRcpServerWizardPage)
				finish =  newXmlRcpServerWizardPage.isPageComplete();
			else if (usedServerPage instanceof NewSocketServerWizardPage)
				finish = newSocketServerWizardPage.isPageComplete();
		}
		return finish;
	}

	@Override
	public void addPages() {
		setNeedsProgressMonitor(true);
		selectServerTypeWizardPage = new SelectServerTypeWizardPage("Select Server Type");
		newXmlRcpServerWizardPage = new NewXmlRcpServerWizardPage(Messages.NewServerWizard_2);
		newSocketServerWizardPage = new NewSocketServerWizardPage("New Socket Server");
		
		addPage(selectServerTypeWizardPage);
		addPage(newXmlRcpServerWizardPage);
		addPage(newSocketServerWizardPage);
		usedServerPage = newXmlRcpServerWizardPage;
	}
	
	@Override
	public boolean performFinish() {
		Server server = null;
		if (usedServerPage instanceof NewXmlRcpServerWizardPage)
			server = newXmlRcpServerWizardPage.getServer();
		else if (usedServerPage instanceof NewSocketServerWizardPage)
			server = newSocketServerWizardPage.getServer();
		else
			return false;
		server.setI8Support(selectServerTypeWizardPage.isI8Supported());
		
		ServerManager sm = AnotherTorrentCore.getDefault().getServerManager();
		if (edit)
			sm.removeServer(this.server);
		sm.addServer(server);
		sm.save();
		ServerView.setInput(sm);
		return true;
	}
	
	public void setInput(Server server)
	{
		this.server = server;
		this.edit = true;
	}
}
